package com.eva.config.security;

import com.alibaba.fastjson.JSON;
import com.eva.api.BaseController;
import com.eva.core.model.ApiResponse;
import com.eva.core.utils.Utils;
import com.eva.dao.system.model.SystemInterfaceConfig;
import com.eva.service.system.SystemInterfaceConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 响应参数处理
 * @author Caesar Liu
 * @date 2022-04-06 00:19
 */
@Slf4j
@Component
@RestControllerAdvice(basePackageClasses = BaseController.class)
public class SecurityResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private SystemInterfaceConfigService systemInterfaceConfigService;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return Boolean.TRUE;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (!(o instanceof ApiResponse)) {
            return o;
        }
        HttpServletRequest httpServletRequest = ((ServletServerHttpRequest)serverHttpRequest).getServletRequest();
        // 不需要加密
        if (Utils.Secure.disallowEncrypt(httpServletRequest)) {
            return o;
        }
        // URI不匹配
        String uri = httpServletRequest.getRequestURI();
        uri = uri.replace(httpServletRequest.getContextPath(), "");
        SystemInterfaceConfig interfaceConfig = systemInterfaceConfigService.match(uri);
        if (interfaceConfig == null || !interfaceConfig.getEnableEncrypt()) {
            return o;
        }
        // 加密ApiResponse
        try {
            String responseBody = JSON.toJSONString(o);
            return Utils.Secure.encryptResponse(responseBody);
        } catch (SecurityException e) {
            log.error("EVA: encrypt response throw an exception", e);
        }
        return null;
    }
}
